<template>
  <div class="vip-order-page">

    <!-- 从订单导入提示 -->
    <div v-if="route.query.fromOrder" class="import-notice">
      <van-icon name="info-o" size="16" color="#157658" />
      <span>正在从订单导入商品信息，建议价格已自动设置</span>
    </div>

    <!-- 商品列表 -->
    <div class="order-items">
      <div v-for="item in orderItems" :key="item.sku.id" class="order-item">
        <img :src="item.sku.img" :alt="item.sku.title" class="item-image" />
        <div class="item-info">
          <h4 class="item-title">{{ item.sku.title }}</h4>
          <div class="item-specs">
            <span v-for="spec in item.sku.specs" :key="spec.key" class="spec-item">
              {{ spec.key }}: {{ spec.value }}
            </span>
          </div>
          <div class="item-price">
            <span class="price">¥{{ formatPrice(item.sku.price) }}</span>
            <span class="count">x{{ item.count }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 价格信息 -->
    <div class="price-container">
      <div class="price-row">
        <span class="price-label">商品总金额：</span>
        <span class="price-value">¥{{ formatPrice(totalPrice) }}</span>
      </div>
    </div>

    <!-- 支付信息 -->
    <div class="pay-container">
      <div class="pay-row">
        <span class="pay-label">收款码(长按扫一扫)</span>
      </div>
      <div class="pay-qrcode-row" v-if="salerInfo?.bank_qrcode_url">
        <!-- 加载状态 -->
        <div v-if="qrcodeLoading" class="qrcode-loading">
          <van-loading type="spinner" size="24" color="#157658" />
          <span class="loading-text">收款码加载中...</span>
        </div>
        
        <!-- 图片显示 -->
        <img 
          v-show="!qrcodeLoading"
          :src="salerInfo.bank_qrcode_url" 
          class="pay-qrcode"
          @click="onPreviewQrcode"
          @load="onQrcodeLoad"
          @error="onQrcodeError"
          alt="收款码"
        />
      </div>
      <div class="pay-row">
        <span class="pay-label">上传付款凭证视频</span>
        <van-button 
          type="primary" 
          size="small" 
          @click="onShowVideoHelp"
          icon="video-o"
          class="help-btn"
        >
          演示视频
        </van-button>
      </div>
      <div class="pay-upload-row">
        <!-- 未上传时显示上传区域 -->
        <div v-if="!payVideo" class="pay-upload-box" @click="onChooseVoucher">
          <span class="pay-upload-plus">+</span>
          <span class="pay-upload-text">选择视频</span>
        </div>
        
        <!-- 已上传时显示视频和重新上传按钮 -->
        <div v-else class="uploaded-file-container">
          <!-- 视频文件 -->
          <video 
            ref="videoPlayer"
            :src="payVideo" 
            class="pay-video" 
            @click="onVideoClick"
            @loadstart="onVideoLoadStart"
            @loadedmetadata="onVideoLoadedMetadata"
            @loadeddata="onVideoLoadedData"
            @error="onVideoLoadError"
            @canplay="onVideoCanPlay"
            @dblclick="onVideoDoubleClick"
            controls
            preload="metadata"
            crossorigin="anonymous"
            playsinline
            webkit-playsinline
          >
            您的浏览器不支持视频播放
          </video>
          
          <div class="video-actions">
            <van-button 
              type="warning" 
              size="small" 
              @click="onChooseVoucher"
              icon="video-o"
              class="reupload-btn"
            >
              重新上传
            </van-button>
            
            <van-button 
              v-if="billRecognitionResult"
              type="primary" 
              size="small" 
              @click="showBillRecognitionDialog = true"
              icon="eye-o"
              class="view-recognition-btn"
            >
              查看识别结果
            </van-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部提交 -->
    <div class="bottom-container">
      <div class="price-summary">
        <span class="total-label">合计</span>
        <span class="total-price">¥{{ formatPrice(finalTotalPrice) }}</span>
      </div>
      <van-button 
        type="primary" 
        size="large" 
        :disabled="submitBtnDisable"
        @click="onSubmit"
        class="submit-btn"
      >
        {{ route.query.fromOrder ? '发布二手' : '提交订单' }}
      </van-button>
    </div>

    <!-- 错误提示 -->
    <van-dialog 
      v-model:show="orderFail" 
      title="订单生成失败" 
      :message="orderFailMsg"
      confirm-button-text="确定"
    />

    <!-- 自定义Loading遮罩 -->
    <div v-if="showCustomLoading" class="custom-loading-overlay">
      <div class="custom-loading-content">
        <div class="loading-spinner">
          <div class="spinner"></div>
        </div>
        <div class="loading-text">{{ loadingMessage }}</div>
      </div>
    </div>

    <!-- 页面锁定遮罩 -->
    <div v-if="isPageLocked && !showCustomLoading" class="page-lock-overlay">
      <div class="page-lock-content">
        <div class="lock-icon">
          <van-icon name="lock" size="32" color="#fff" />
        </div>
        <div class="lock-text">{{ lockReason }}</div>
        <div class="lock-tip">请勿进行其他操作</div>
      </div>
    </div>

    <!-- 支付凭证上传演示视频弹窗 -->
    <van-dialog 
      v-model:show="showVideoHelp" 
      title="上传支付凭证视频演示"
      :show-confirm-button="true"
      confirm-button-text="关闭"
      class="video-help-dialog"
    >
      <div class="video-help-content">
        <video 
          ref="helpVideo"
          class="help-video" 
          :src="videoHelpUrl" 
          controls
          preload="metadata"
          @error="onVideoError"
        >
          您的浏览器不支持视频播放
        </video>
        
        <div class="video-tips">
          <h4 class="tip-title">操作步骤：</h4>
          <div class="tip-list">
            <div class="tip-item">
              <span class="tip-number">1</span>
              <span>完成支付后，使用手机相机录制支付凭证视频</span>
            </div>
            <div class="tip-item">
              <span class="tip-number">2</span>
              <span>确保视频清晰可见，避免使用录屏软件</span>
            </div>
            <div class="tip-item">
              <span class="tip-number">3</span>
              <span>点击"选择视频"按钮上传</span>
            </div>
            <div class="tip-item">
              <span class="tip-number">4</span>
              <span>确认视频清晰可见，时长适中</span>
            </div>
          </div>
          <div class="format-tips">
            <p class="format-warning">⚠️ 重要提示：请使用手机相机录制，确保视频清晰可见，避免使用第三方录屏软件</p>
          </div>
        </div>
      </div>
    </van-dialog>

    <!-- 全屏视频播放对话框 -->
    <van-dialog 
      v-model:show="showVideoDialog" 
      title="付款凭证视频"
      :show-confirm-button="true"
      confirm-button-text="关闭"
      class="fullscreen-video-dialog"
      :close-on-click-overlay="true"
    >
      <div class="fullscreen-video-content">
        <video 
          ref="fullscreenVideo"
          class="fullscreen-video" 
          :src="fullscreenVideoUrl" 
          controls
          preload="metadata"
          @error="onVideoError"
          @dblclick="onFullscreenVideoDoubleClick"
          playsinline
          webkit-playsinline
        >
          您的浏览器不支持视频播放
        </video>
        <div class="video-tips">
          <p class="tip-text">💡 双击视频可全屏播放</p>
        </div>
      </div>
    </van-dialog>

    <!-- 账单识别结果对话框 -->
    <van-dialog 
      v-model:show="showBillRecognitionDialog" 
      title="支付凭证确认"
      :show-confirm-button="false"
      :show-cancel-button="false"
      class="bill-recognition-dialog"
      :close-on-click-overlay="false"
    >
      <div class="bill-recognition-content" v-if="billRecognitionResult">
        <!-- 识别状态 -->
        <div class="recognition-status">
          <div class="status-item">
            <span class="status-label">账单查询视频：</span>
            <span class="status-value" :class="billRecognitionResult.is_bill_query ? 'success' : 'fail'">
              {{ billRecognitionResult.is_bill_query ? '✓ 是' : '✗ 否' }}
            </span>
          </div>
          <div class="status-item">
            <span class="status-label">手机桌面进入：</span>
            <span class="status-value" :class="billRecognitionResult.is_from_desktop ? 'success' : 'fail'">
              {{ billRecognitionResult.is_from_desktop ? '✓ 是' : '✗ 否' }}
            </span>
          </div>
        </div>
        
        <!-- 验证状态提示 -->
        <div class="validation-status" :class="billRecognitionResult.verificationStatus === 'verified' ? 'success' : 'failed'">
          <van-icon 
            :name="billRecognitionResult.verificationStatus === 'verified' ? 'success' : 'warning-o'" 
            :color="billRecognitionResult.verificationStatus === 'verified' ? '#157658' : '#ff6b6b'" 
            size="20" 
          />
          <span class="status-text">
            {{ billRecognitionResult.verificationStatus === 'verified' ? '支付凭证验证通过！' : '支付凭证验证失败！' }}
          </span>
        </div>
        
        <!-- 验证失败详情 -->
        <div v-if="billRecognitionResult.verificationStatus !== 'verified'" class="validation-details">
          <div v-if="!billRecognitionResult.payeeMatch" class="validation-error">
            <van-icon name="warning-o" color="#ff6b6b" size="16" />
            <span>收款方不匹配：识别为"{{ billRecognitionResult.payeeName || '未识别' }}"，实际应为"{{ billRecognitionResult.merchantName || '未知' }}"</span>
          </div>
          <div v-if="billRecognitionResult.orderDuplicate" class="validation-error">
            <van-icon name="warning-o" color="#ff6b6b" size="16" />
            <span>订单号重复：{{ billRecognitionResult.orderNumber || '未知订单号' }} 已存在</span>
          </div>
          
          <!-- 强制提交提示 -->
          <div class="force-submit-tips">
            <van-icon name="info-o" color="#ff9500" size="16" />
            <span>如您确认支付凭证真实有效，可选择强制提交交由人工审核</span>
          </div>
        </div>

        <!-- 账单信息 -->
        <div v-if="billRecognitionResult.is_bill_query && billRecognitionResult.is_from_desktop" class="bill-info">
          <h4 class="bill-title">识别到的账单信息</h4>
          <div class="bill-details">
            <div class="bill-item" v-if="billRecognitionResult.payment_amount">
              <span class="bill-label">支付金额：</span>
              <span class="bill-value amount">¥{{ formatBillAmount(billRecognitionResult.payment_amount) }}</span>
            </div>
            <div class="bill-item" v-if="billRecognitionResult.payee_name">
              <span class="bill-label">收款方：</span>
              <span class="bill-value">{{ billRecognitionResult.payee_name }}</span>
            </div>
            <div class="bill-item" v-if="billRecognitionResult.order_number">
              <span class="bill-label">订单号：</span>
              <span class="bill-value order-number">{{ billRecognitionResult.order_number }}</span>
            </div>
            <div class="bill-item" v-if="billRecognitionResult.payment_time">
              <span class="bill-label">支付时间：</span>
              <span class="bill-value">{{ billRecognitionResult.payment_time }}</span>
            </div>
            <div class="bill-item" v-if="billRecognitionResult.payment_method">
              <span class="bill-label">支付方式：</span>
              <span class="bill-value">{{ billRecognitionResult.payment_method }}</span>
            </div>
            <div class="bill-item" v-if="billRecognitionResult.remark">
              <span class="bill-label">备注：</span>
              <span class="bill-value">{{ billRecognitionResult.remark }}</span>
            </div>
          </div>
        </div>
        
        <!-- 确认提示 -->
        <div class="confirmation-tips">
          <p class="tip-text">请仔细核对以上信息是否正确</p>
          <p class="tip-detail">如果信息有误，请点击"重新上传"重新录制视频</p>
        </div>

        <!-- 识别置信度 -->
        <div class="confidence-info" v-if="billRecognitionResult.confidence">
          <span class="confidence-label">识别置信度：</span>
          <span class="confidence-value" :class="getConfidenceClass(billRecognitionResult.confidence)">
            {{ Math.round(billRecognitionResult.confidence * 100) }}%
          </span>
        </div>

        <!-- 提示信息 -->
        <div v-if="!billRecognitionResult.is_bill_query || !billRecognitionResult.is_from_desktop" class="recognition-tips">
          <p class="tip-text">⚠️ 视频内容不符合账单识别要求</p>
          <p class="tip-detail">请确保视频包含账单查询操作，且从桌面进入银行或支付宝app</p>
        </div>
      </div>
      
      <!-- 自定义按钮区域 -->
      <div class="dialog-actions">
        <van-button 
          type="default" 
          size="large" 
          @click="onRejectBillRecognition"
          class="action-button"
        >
          重新上传
        </van-button>
        
        <!-- 验证通过时显示确认按钮 -->
        <van-button 
          v-if="billRecognitionResult?.verificationStatus === 'verified'"
          type="primary" 
          size="large" 
          @click="onConfirmBillRecognition"
          class="action-button"
        >
          确认无误
        </van-button>
        
        <!-- 验证失败时显示强制提交按钮 -->
        <van-button 
          v-else
          type="warning" 
          size="large" 
          @click="onForceSubmit"
          class="action-button"
        >
          强制提交人工审核
        </van-button>
      </div>
    </van-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { showToast, showLoadingToast, closeToast, showImagePreview, showConfirmDialog } from 'vant'
import { getSkusByIds } from '@/api/sku'
import { getUserInfo } from '@/api/user'
import { createVipOrder, getOrderDetail } from '@/api/order'

import { uploadVideo } from '@/api/upload'
import api from '@/api'

const route = useRoute()
const router = useRouter()

// 响应式数据
const orderItems = ref([])
const totalPrice = ref(0)
const finalTotalPrice = ref(0)
const submitBtnDisable = ref(false)
const currentOrderId = ref(null) // 当前订单ID
const orderFail = ref(false)
const orderFailMsg = ref('')
const salerInfo = ref(null)
const payVideo = ref('')
const qrcodeLoading = ref(false)

// 自定义Loading相关
const showCustomLoading = ref(false)
const loadingMessage = ref('')

// 页面锁定相关
const isPageLocked = ref(false)
const lockReason = ref('')

// 自定义Loading控制函数
const showCustomLoadingToast = (message) => {
  loadingMessage.value = message
  showCustomLoading.value = true
  console.log('自定义Loading显示:', message)
}

const hideCustomLoadingToast = () => {
  showCustomLoading.value = false
  loadingMessage.value = ''
  console.log('自定义Loading隐藏')
}

// 页面锁定控制函数
const lockPage = (reason) => {
  isPageLocked.value = true
  lockReason.value = reason
  console.log('页面已锁定:', reason)
}

const unlockPage = () => {
  isPageLocked.value = false
  lockReason.value = ''
  console.log('页面已解锁')
}

// 视频帮助相关
const showVideoHelp = ref(false)
const videoHelpUrl = ref('https://your-video-url.com/payment-demo.mp4') // 替换为实际的演示视频URL
const helpVideo = ref(null)

// 视频播放相关
const videoPlayer = ref(null)
const showVideoDialog = ref(false)
const fullscreenVideoUrl = ref('')

// 账单识别相关
const billRecognitionResult = ref(null)
const showBillRecognitionDialog = ref(false)

// 格式化价格
const formatPrice = (price) => {
  if (!price) return '0.00'
  return parseFloat(price).toFixed(2)
}

// 带账单识别的视频上传
const uploadVideoWithBillRecognition = async (file) => {
  const formData = new FormData()
  formData.append('file', file)
  
  try {
    console.log('发送上传请求到:', '/file/upload/video-with-bill-recognition')
    const response = await api.post('/file/upload/video-with-bill-recognition', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    console.log('API原始响应:', response)
    console.log('响应数据类型:', typeof response)
    
    // 检查响应结构
    if (response && typeof response === 'object') {
      console.log('响应包含的键:', Object.keys(response))
      return response
    } else {
      console.error('响应格式异常:', response)
      throw new Error('响应格式异常')
    }
  } catch (error) {
    console.error('上传视频失败:', error)
    console.error('错误详情:', {
      message: error.message,
      response: error.response,
      status: error.response?.status,
      data: error.response?.data
    })
    throw error
  }
}

// 格式化账单金额
const formatBillAmount = (amountInCents) => {
  if (!amountInCents) return '0.00'
  return (amountInCents / 100).toFixed(2)
}

// 获取置信度样式类
const getConfidenceClass = (confidence) => {
  if (confidence >= 0.8) return 'high'
  if (confidence >= 0.6) return 'medium'
  return 'low'
}

// 确认账单识别结果
const onConfirmBillRecognition = () => {
  showBillRecognitionDialog.value = false
  showToast({
    type: 'success',
    message: '支付凭证已确认，可以提交订单',
    duration: 2000
  })
  
  // 不直接跳转，让用户点击提交订单按钮
  // 这样可以通过正常的验证流程
}

// 拒绝账单识别结果，重新上传
const onRejectBillRecognition = () => {
  showBillRecognitionDialog.value = false
  
  // 清除已上传的视频和识别结果
  payVideo.value = ''
  billRecognitionResult.value = null
  
  showToast({
    type: 'warning',
    message: '请重新上传支付凭证',
    duration: 2000
  })
}

// 强制提交人工审核
const onForceSubmit = async () => {
  try {
    await showConfirmDialog({
      title: '强制提交确认',
      message: '您确定要强制提交此支付凭证吗？系统将跳过自动验证，交由人工审核。'
    })
    
    // 调用后端API进行强制提交
    try {
      const response = await api.post('/v1/test/force-submit', {
        paymentProofId: billRecognitionResult.value.paymentProofId,
        reason: '用户确认支付凭证真实有效，但自动验证失败',
        userRemark: '用户强制提交，请人工审核'
      })
      
      console.log('强制提交API响应:', response)
      console.log('响应数据:', response)
      console.log('success字段:', response?.success)
      
      if (response?.success) {
        showBillRecognitionDialog.value = false
        showToast({
          type: 'success',
          message: '支付凭证已提交人工审核，请等待审核结果',
          duration: 3000
        })
        
        // 跳转到订单中心页面
        setTimeout(() => {
          router.push('/my-order-center')
        }, 1500)
      } else {
        console.error('API返回失败:', response)
        throw new Error(response?.message || '提交失败')
      }
    } catch (apiError) {
      console.error('强制提交API调用失败:', apiError)
      showToast('提交失败，请稍后重试')
    }
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('强制提交失败:', error)
      showToast('提交失败，请稍后重试')
    }
  }
}

// 开始账单识别分析
const startBillRecognition = async (videoUrl) => {
  console.log('=== startBillRecognition函数开始执行 ===')
  console.log('传入的videoUrl:', videoUrl)
  
  try {
    // 锁定页面
    lockPage('正在分析视频内容...')
    
    // 显示自定义loading
    console.log('准备显示账单识别loading...')
    showCustomLoadingToast('正在分析视频内容...')
    console.log('账单识别loading已显示')
    
    console.log('开始账单识别分析:', videoUrl)
    
    // 记录开始时间
    const startTime = Date.now()
    console.log('API调用开始时间:', new Date().toLocaleTimeString())
    
    // 获取当前订单信息
    const orderId = currentOrderId.value
    if (!orderId) {
      throw new Error('订单ID不存在，请重新进入页面')
    }
    
    // 获取用户ID
    let userId = 1 // 默认值
    try {
      const userInfo = await getUserInfo()
      if (userInfo && userInfo.id) {
        userId = userInfo.id
      }
    } catch (error) {
      console.warn('获取用户信息失败，使用默认用户ID:', error)
    }
    
    // 获取卖家ID
    const salerId = salerInfo.value?.id
    if (!salerId) {
      throw new Error('卖家信息不存在，无法进行账单识别')
    }
    
    // 调用账单识别和验证API
    const recognitionResponse = await api.post('/v1/test/bill-recognition', {
      video_url: videoUrl,
      order_id: orderId,
      user_id: userId,
      saler_id: salerId
    })
    
    // 记录结束时间
    const endTime = Date.now()
    const duration = (endTime - startTime) / 1000
    console.log('API调用结束时间:', new Date().toLocaleTimeString())
    console.log('API调用耗时:', duration + '秒')
    console.log('账单识别响应:', recognitionResponse)
    
    // 检查响应是否有效
    if (!recognitionResponse) {
      closeToast()
      throw new Error('账单识别响应为空')
    }
    
    if (recognitionResponse.success) {
      // 处理新的验证结果结构
      const recognitionData = recognitionResponse.recognition || {}
      const verificationData = recognitionResponse.verification || {}
      const overallSuccess = recognitionResponse.overallSuccess
      
      console.log('账单识别成功:', recognitionData)
      console.log('验证结果:', verificationData)
      console.log('整体验证状态:', overallSuccess)
      console.log('识别到的收款方:', recognitionData.billInfo?.payee_name || recognitionData.billInfo?.payeeName)
      console.log('识别到的订单号:', recognitionData.billInfo?.order_number || recognitionData.billInfo?.orderNumber)
      console.log('验证的商户名称:', verificationData?.merchantName)
      
      // 关闭loading状态
      console.log('准备关闭账单识别loading...')
      hideCustomLoadingToast()
      console.log('账单识别loading已关闭')
      
      // 解锁页面
      unlockPage()
      
      // 设置识别结果，包含验证信息
      const billInfo = recognitionData.billInfo || {}
      billRecognitionResult.value = {
        ...billInfo,
        // 确保字段名正确映射
        payeeName: billInfo.payee_name || billInfo.payeeName || '未识别',
        orderNumber: billInfo.order_number || billInfo.orderNumber || '未知订单号',
        paymentAmount: billInfo.payment_amount || billInfo.paymentAmount || 0,
        paymentTime: billInfo.payment_time || billInfo.paymentTime || '',
        paymentMethod: billInfo.payment_method || billInfo.paymentMethod || '未知支付方式',
        isBillQuery: billInfo.is_bill_query || billInfo.isBillQuery || false,
        isFromDesktop: billInfo.is_from_desktop || billInfo.isFromDesktop || false,
        // 验证信息
        verificationStatus: verificationData?.verificationStatus || 'failed',
        payeeMatch: verificationData?.payeeMatch || false,
        orderDuplicate: verificationData?.orderDuplicate || false,
        merchantName: verificationData?.merchantName || '未知商户',
        // 支付凭证ID（用于强制提交）
        paymentProofId: verificationData?.paymentProofId
      }
      
      // 根据验证结果显示不同的消息
      if (overallSuccess) {
        showToast({
          type: 'success',
          message: '支付凭证验证通过！',
          duration: 2000
        })
      } else {
        showToast({
          type: 'warning',
          message: '支付凭证验证失败，请检查收款方和订单号',
          duration: 3000
        })
      }
      
      // 显示识别结果对话框让用户确认
      showBillRecognitionDialog.value = true
    } else {
      // 关闭loading状态
      hideCustomLoadingToast()
      
      // 解锁页面
      unlockPage()
      
      // 账单识别失败
      console.log('账单识别失败:', recognitionResponse.error)
      showToast({
        type: 'fail',
        message: '账单识别失败，请重新上传',
        duration: 3000
      })
      
      // 清除已上传的视频
      payVideo.value = ''
      billRecognitionResult.value = null
    }
  } catch (error) {
    console.error('账单识别失败:', error)
    console.error('错误详情:', {
      message: error.message,
      response: error.response,
      status: error.response?.status,
      data: error.response?.data
    })
    
    hideCustomLoadingToast()
    // 解锁页面
    unlockPage()
    showToast({
      type: 'fail',
      message: '账单识别失败，请重新上传',
      duration: 3000
    })
    
    // 清除已上传的视频
    payVideo.value = ''
    billRecognitionResult.value = null
  }
  
  console.log('=== startBillRecognition函数执行完成 ===')
}

// 创建订单
const createOrder = async (sku, count) => {
  try {
    console.log('开始创建订单:', { skuId: sku.id, count })
    
    const orderData = {
      total_price: sku.price * count,
      final_total_price: sku.price * count,
      sku_info_list: [{
        id: sku.id, // 注意：后端期望的是id字段，不是skuId
        count: count
      }],
      address: null, // 暂时不设置地址
      saler: sku.saler || (sku.spu && sku.spu.user_id) || 1,
      type: 'vip'
    }
    
    const response = await createVipOrder(orderData)
    if (response && response.id) {
      currentOrderId.value = response.id
      console.log('订单创建成功，订单ID:', currentOrderId.value)
    } else {
      throw new Error('订单创建失败')
    }
  } catch (error) {
    console.error('创建订单失败:', error)
    showToast('创建订单失败: ' + error.message)
    throw error
  }
}

// 获取订单商品
const getOrderItems = async () => {
  try {
    // 检查是否从订单导入
    const fromOrder = route.query.fromOrder
    if (fromOrder) {
      await loadFromOrder(fromOrder)
      return
    }
    
    // 原有的SKU逻辑
    const skuId = route.query.sku_id
    const count = parseInt(route.query.count) || 1
    
    if (!skuId) {
      showToast('商品ID不能为空')
      return
    }
    
    const skus = await getSkusByIds(skuId)
    if (!skus || skus.length === 0) {
      showToast('商品信息不存在')
      return
    }
    
    const sku = skus[0]
    orderItems.value = [{
      sku: sku,
      count: count
    }]
    
    // 计算总价
    totalPrice.value = sku.price * count
    finalTotalPrice.value = totalPrice.value
    
    // 创建订单
    await createOrder(sku, count)
    
    // 获取卖家信息
    try {
      // 启动收款码加载状态
      qrcodeLoading.value = true
      
      if (sku.saler) {
        // 通过saler ID获取卖家信息
        const saler = await getUserInfo(sku.saler)
        salerInfo.value = saler
      } else if (sku.spu && sku.spu.user_id) {
        // 从SPU获取卖家信息 - 需要调用API获取收款码信息
        try {
          const saler = await getUserInfo(sku.spu.user_id)
          salerInfo.value = saler
        } catch (error) {
          console.error('获取卖家收款码信息失败:', error)
          // 如果获取失败，使用默认值
          salerInfo.value = {
            id: sku.spu.user_id,
            nickname: '卖家',
            bank_qrcode_url: 'https://example.com/default-qrcode.jpg'
          }
        }
      } else {
        // 普通商品没有卖家，使用当前用户的收款码信息
        try {
          const userResponse = await getUserInfo()
          if (userResponse && userResponse.bank_qrcode_url) {
            salerInfo.value = {
              id: userResponse.id || 0,
              nickname: userResponse.nickname || '当前用户',
              bank_qrcode_url: userResponse.bank_qrcode_url
            }
          } else {
            // 如果用户也没有收款码，使用默认值
            salerInfo.value = {
              id: 0,
              nickname: '平台',
              bank_qrcode_url: 'https://example.com/default-qrcode.jpg'
            }
          }
        } catch (error) {
          console.error('获取用户收款码信息失败:', error)
          // 获取失败时使用默认值
          salerInfo.value = {
            id: 0,
            nickname: '平台',
            bank_qrcode_url: 'https://example.com/default-qrcode.jpg'
          }
        }
      }
    } catch (error) {
      console.error('获取卖家信息失败:', error)
      // 获取失败时使用默认值
      salerInfo.value = {
        id: 0,
        nickname: '平台',
        bank_qrcode_url: 'https://example.com/default-qrcode.jpg'
      }
    }
    
  } catch (error) {
    console.error('获取订单商品失败:', error)
    showToast('获取商品信息失败')
  }
}

// 从订单导入商品信息
const loadFromOrder = async (orderId) => {
  try {
    // 获取订单详情
    const response = await getOrderDetail(orderId)
    if (!response.success) {
      throw new Error(response.message || '获取订单信息失败')
    }
    
    const order = response.data
    
    // 设置建议价格
    const suggestedPrice = route.query.suggestedPrice || order.finalTotalPrice || order.totalPrice
    totalPrice.value = suggestedPrice
    finalTotalPrice.value = suggestedPrice
    
    // 解析商品信息
    let productInfo = null
    if (route.query.productInfo) {
      try {
        productInfo = JSON.parse(route.query.productInfo)
      } catch (e) {
        console.error('解析商品信息失败:', e)
      }
    }
    
    // 构建商品项
    if (productInfo && productInfo.specs) {
      // 如果有规格信息，使用规格信息
      orderItems.value = [{
        sku: {
          id: `order_${orderId}`,
          title: productInfo.title || '二手商品',
          img: productInfo.image || order.snapImg,
          price: suggestedPrice,
          specs: productInfo.specs
        },
        count: 1
      }]
    } else {
      // 使用订单快照信息
      orderItems.value = [{
        sku: {
          id: `order_${orderId}`,
          title: order.snapTitle || '二手商品',
          img: order.snapImg,
          price: suggestedPrice,
          specs: []
        },
        count: 1
      }]
    }
    
    // 设置页面标题
    document.title = '发布二手商品'
    
  } catch (error) {
    console.error('从订单导入失败:', error)
    showToast('导入订单信息失败')
  }
}

// 生成伪造的地址信息
const generateFakeAddress = () => {
  const fakeAddresses = [
    {
      id: 1,
      name: '张三',
      mobile: '13800138000',
      province: '广东省',
      city: '深圳市',
      district: '南山区',
      detail: '科技园南区深南大道10000号',
      is_default: true
    },
    {
      id: 2,
      name: '李四',
      mobile: '13900139000',
      province: '北京市',
      city: '北京市',
      district: '朝阳区',
      detail: '三里屯街道工体北路8号',
      is_default: false
    },
    {
      id: 3,
      name: '王五',
      mobile: '13700137000',
      province: '上海市',
      city: '上海市',
      district: '浦东新区',
      detail: '陆家嘴金融贸易区世纪大道88号',
      is_default: false
    }
  ]
  
  // 随机选择一个地址
  const randomIndex = Math.floor(Math.random() * fakeAddresses.length)
  return fakeAddresses[randomIndex]
}

// 预览收款码
const onPreviewQrcode = () => {
  if (salerInfo.value?.bank_qrcode_url) {
    // 这里可以使用图片预览组件
    window.open(salerInfo.value.bank_qrcode_url)
  } else {
    showToast('无可预览图片')
  }
}

// 收款码图片加载完成
const onQrcodeLoad = () => {
  console.log('收款码图片加载完成')
  qrcodeLoading.value = false
}

// 收款码图片加载失败
const onQrcodeError = () => {
  console.error('收款码图片加载失败')
  qrcodeLoading.value = false
  showToast('收款码加载失败，请刷新重试')
}

// 选择付款凭证
const onChooseVoucher = () => {
  // 检查页面是否已锁定
  if (isPageLocked.value) {
    showToast({
      type: 'warning',
      message: '正在处理中，请稍候...'
    })
    return
  }
  
  // 创建文件输入元素
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = 'video/*'
  input.onchange = async (event) => {
    const file = event.target.files[0]
    if (!file) return
    
    console.log('选择的文件:', file)
    
    // 验证文件大小（限制为50MB）
    if (file.size > 50 * 1024 * 1024) {
      showToast({
        type: 'fail',
        message: '视频大小不能超过50MB'
      })
      return
    }
    
    // 验证文件类型
    if (!file.type.startsWith('video/')) {
      showToast({
        type: 'fail',
        message: '请选择视频文件'
      })
      return
    }
    
    // 记录视频格式信息（用于调试）
    console.log('上传视频格式:', file.type)
    
    try {
      // 锁定页面
      lockPage('正在上传视频...')
      
      showLoadingToast({
        message: '上传中...',
        forbidClick: true,
      })
      
      console.log('开始调用上传API...')
      // 使用带账单识别的上传接口
      const response = await uploadVideoWithBillRecognition(file)
      console.log('上传API响应:', response)
      console.log('响应类型:', typeof response)
      console.log('响应是否为null:', response === null)
      console.log('响应是否为undefined:', response === undefined)
      
      // 检查响应是否有效
      if (!response) {
        console.error('上传响应为空，响应详情:', response)
        throw new Error('上传响应为空')
      }
      
      // 根据后端API响应结构设置视频URL
      if (response.success && response.url) {
        const videoUrl = response.url
        
        // 使用代理接口解决CORS问题，使用相对路径
        const proxyUrl = `/v1/file/proxy/video?url=${encodeURIComponent(videoUrl)}`
        payVideo.value = proxyUrl
        console.log('原始视频URL:', videoUrl)
        console.log('使用代理URL:', proxyUrl)
        console.log('视频文件信息:', {
          name: file.name,
          size: file.size,
          type: file.type
        })
        
        // 显示转换状态
        if (response.converted) {
          console.log('视频已自动转换:', response.conversionInfo)
        }
        
        // 第一阶段：上传完成，显示成功提示
        closeToast()
        showToast({
          type: 'success',
          message: '视频上传成功！',
          duration: 2000
        })
        
        // 第二阶段：开始账单识别分析
        setTimeout(async () => {
          console.log('准备开始账单识别分析...')
          // 确保之前的toast完全关闭，增加延迟时间
          await new Promise(resolve => setTimeout(resolve, 500))
          console.log('开始调用startBillRecognition函数...')
          await startBillRecognition(videoUrl)
          console.log('startBillRecognition函数调用完成')
        }, 2500) // 增加延迟时间，确保上传成功的toast完全消失
        
        // 移除视频测试，避免干扰loading状态
      } else {
        throw new Error(response.message || '上传失败')
      }
      
    } catch (error) {
      console.error('上传失败:', error)
      closeToast()
      // 解锁页面
      unlockPage()
      showToast({
        type: 'fail',
        message: error.message || '视频上传失败',
        duration: 2000
      })
    }
  }
  input.click()
}

// 视频点击事件
const onVideoClick = () => {
  // 检查页面是否已锁定
  if (isPageLocked.value) {
    showToast({
      type: 'warning',
      message: '正在处理中，请稍候...'
    })
    return
  }
  
  if (payVideo.value) {
    // 显示全屏视频播放对话框
    fullscreenVideoUrl.value = payVideo.value
    showVideoDialog.value = true
  } else {
    showToast('暂无付款凭证')
  }
}

// 视频双击事件（全屏播放）
const onVideoDoubleClick = () => {
  if (videoPlayer.value) {
    if (videoPlayer.value.requestFullscreen) {
      videoPlayer.value.requestFullscreen()
    } else if (videoPlayer.value.webkitRequestFullscreen) {
      videoPlayer.value.webkitRequestFullscreen()
    } else if (videoPlayer.value.mozRequestFullScreen) {
      videoPlayer.value.mozRequestFullScreen()
    } else if (videoPlayer.value.msRequestFullscreen) {
      videoPlayer.value.msRequestFullscreen()
    }
  }
}

// 预览付款凭证（保留原有功能）
const onPreviewVoucher = () => {
  onVideoClick()
}

// 显示视频帮助
const onShowVideoHelp = () => {
  showVideoHelp.value = true
}

// 视频播放错误处理
const onVideoError = (error) => {
  console.error('视频播放错误:', error)
  // 移除错误提示，不显示弹窗
}

// 视频加载开始
const onVideoLoadStart = () => {
  console.log('视频开始加载...')
}

// 视频元数据加载完成
const onVideoLoadedMetadata = () => {
  console.log('视频元数据加载完成')
  if (videoPlayer.value) {
    console.log('视频元数据:', {
      duration: videoPlayer.value.duration,
      videoWidth: videoPlayer.value.videoWidth,
      videoHeight: videoPlayer.value.videoHeight,
      currentSrc: videoPlayer.value.currentSrc
    })
    
    // 移除所有视频验证逻辑，不进行任何检查
  }
}

// 视频数据加载完成
const onVideoLoadedData = () => {
  console.log('视频数据加载完成')
  if (videoPlayer.value) {
    console.log('视频信息:', {
      duration: videoPlayer.value.duration,
      videoWidth: videoPlayer.value.videoWidth,
      videoHeight: videoPlayer.value.videoHeight,
      readyState: videoPlayer.value.readyState,
      networkState: videoPlayer.value.networkState
    })
  }
}

// 视频加载错误
const onVideoLoadError = (error) => {
  console.error('视频加载错误:', error)
  console.error('视频URL:', payVideo.value)
  // 移除错误提示，不显示弹窗
}

// 视频可以播放
const onVideoCanPlay = () => {
  console.log('视频可以播放')
}

// 全屏视频双击事件
const onFullscreenVideoDoubleClick = () => {
  const fullscreenVideo = document.querySelector('.fullscreen-video')
  if (fullscreenVideo) {
    if (fullscreenVideo.requestFullscreen) {
      fullscreenVideo.requestFullscreen()
    } else if (fullscreenVideo.webkitRequestFullscreen) {
      fullscreenVideo.webkitRequestFullscreen()
    } else if (fullscreenVideo.mozRequestFullScreen) {
      fullscreenVideo.mozRequestFullScreen()
    } else if (fullscreenVideo.msRequestFullscreen) {
      fullscreenVideo.msRequestFullscreen()
    }
  }
}

// 移除测试视频播放函数，避免干扰loading状态





// 提交订单
const onSubmit = async () => {
  // 检查页面是否已锁定
  if (isPageLocked.value) {
    showToast({
      type: 'warning',
      message: '正在处理中，请稍候...'
    })
    return
  }
  
  if (!orderItems.value.length) {
    showToast('订单商品不能为空')
    return
  }
  
  // 检查是否已上传支付视频
  if (!payVideo.value) {
    showToast({
      type: 'warning',
      message: '请先上传支付凭证视频'
    })
    return
  }
  
  // 检查收款码状态
  const { checkQrcodeStatus } = await import('@/utils/qrcode-validator')
  const qrcodeValid = await checkQrcodeStatus(router.push)
  
  if (!qrcodeValid) {
    submitBtnDisable.value = false
    return // 收款码验证失败，已显示提示并跳转
  }
  
  submitBtnDisable.value = true
  
  try {
    // 构建订单数据（与微信小程序VipOrderPost保持一致）
    const orderData = {
      total_price: totalPrice.value,
      final_total_price: finalTotalPrice.value,
      coupon_id: null, // 修正字段名
      sku_info_list: orderItems.value.map(item => ({
        id: item.sku.id,
        count: item.count
      })),
      address: generateFakeAddress(), // 使用伪造的地址信息
      saler: salerInfo.value?.id || orderItems.value[0]?.sku?.spu?.user_id || 0, // 优先使用卖家ID，其次使用SPU的user_id
      type: orderItems.value[0]?.sku?.root_category_id === 5 ? 'vip' : 'normal', // 根据商品类型判断
      checked: 0, // 添加缺失字段
      pay_image: payVideo.value
    }
    
    console.log('VIP订单数据:', orderData)
    console.log('卖家信息:', salerInfo.value)
    
    // 创建订单（根据类型选择API）
    let orderResponse
    if (orderData.type === 'vip') {
      orderResponse = await createVipOrder(orderData)
    } else {
      // 普通商品订单也使用VIP订单API，因为现在都使用支付凭证支付
      orderResponse = await createVipOrder(orderData)
    }
    
    console.log('订单创建响应:', orderResponse)
    
    if (!orderResponse || !orderResponse.id) {
      throw new Error('创建订单失败')
    }
    
    const orderId = orderResponse.id // 提取订单ID
    console.log('提取的订单ID:', orderId)
    
    showLoadingToast({
      message: '正在创建订单...',
      forbidClick: true,
    })
    
    // VIP订单不走微信支付，直接跳转到我的订单页面
    closeToast()
    
    const isFromOrder = route.query.fromOrder
    const successMessage = isFromOrder ? '二手商品发布成功！' : '订单创建成功，请等待卖家确认支付'
    
    showToast({
      type: 'success',
      message: successMessage
    })
    
    // 跳转到订单中心页面
    setTimeout(() => {
      if (isFromOrder) {
        // 发布二手成功后，跳转到订单中心页面
        router.push('/my-order-center')
      } else {
        // 普通VIP订单，跳转到订单中心页面
        router.push('/my-order-center')
      }
    }, 1500)
    
  } catch (error) {
    submitBtnDisable.value = false
    orderFail.value = true
    orderFailMsg.value = error.message || '订单创建失败'
  }
}

// 组件挂载时获取数据
onMounted(async () => {
  console.log('VIP订单页面挂载')
  console.log('初始 payVideo:', payVideo.value)
  
  // 检查收款码状态（页面级验证）
  const { quickCheckQrcode } = await import('@/utils/qrcode-validator')
  const qrcodeCheck = await quickCheckQrcode()
  
  if (!qrcodeCheck.valid) {
    // 收款码状态不满足要求，显示提示并跳转
    showToast(qrcodeCheck.message)
    
    // 延迟跳转，让用户看到提示
    setTimeout(() => {
      router.push('/my-qrcode')
    }, 1500)
    
    return // 阻止页面继续加载
  }
  
  // 收款码验证通过，继续加载页面
  getOrderItems()
})
</script>

<style lang="scss" scoped>
.vip-order-page {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 100px;
}

.import-notice {
  background: linear-gradient(135deg, #e8f5e8 0%, #d4edda 100%);
  padding: 12px 16px;
  margin: 12px 0;
  border-radius: 10px;
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 14px;
  color: #157658;
  border: 1px solid #c3e6cb;
  box-shadow: 0 2px 8px rgba(21, 118, 88, 0.1);
  
  .van-icon {
    filter: drop-shadow(0 1px 2px rgba(21, 118, 88, 0.2));
  }
}

.order-items {
  background: #fff;
  margin-bottom: 10px;
  
  .order-item {
    display: flex;
    padding: 15px;
    border-bottom: 1px solid #eee;
    
    &:last-child {
      border-bottom: none;
    }
    
    .item-image {
      width: 80px;
      height: 80px;
      object-fit: cover;
      border-radius: 8px;
      margin-right: 15px;
    }
    
    .item-info {
      flex: 1;
      
      .item-title {
        font-size: 16px;
        color: #333;
        margin-bottom: 8px;
        line-height: 1.4;
      }
      
      .item-specs {
        margin-bottom: 8px;
        
        .spec-item {
          display: inline-block;
          font-size: 12px;
          color: #666;
          background: #f5f5f5;
          padding: 2px 6px;
          border-radius: 4px;
          margin-right: 5px;
          margin-bottom: 5px;
        }
      }
      
      .item-price {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .price {
          font-size: 16px;
          font-weight: bold;
          color: #157658;
        }
        
        .count {
          font-size: 14px;
          color: #666;
        }
      }
    }
  }
}

.price-container {
  background: #fff;
  padding: 15px;
  margin-bottom: 10px;
  
  .price-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .price-label {
      font-size: 14px;
      color: #666;
    }
    
    .price-value {
      font-size: 16px;
      color: #333;
      font-weight: bold;
    }
  }
}

.pay-container {
  background: #fff;
  padding: 15px;
  margin-bottom: 10px;
  
  .pay-row {
    margin-bottom: 15px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .pay-label {
      font-size: 14px;
      color: #333;
    }
    
    .help-btn {
      --van-button-small-height: 32px;
      --van-button-small-padding: 0 16px;
      --van-button-small-font-size: 12px;
      --van-button-border-radius: 16px;
      --van-button-primary-background: #157658;
      --van-button-primary-border-color: #157658;
      
      &:hover {
        --van-button-primary-background: #0f5a47;
        --van-button-primary-border-color: #0f5a47;
      }
      
      &:active {
        transform: scale(0.95);
      }
    }
  }
  
  .pay-qrcode-row {
    margin-bottom: 15px;
    position: relative;
    
    .pay-qrcode {
      width: 200px;
      height: 200px;
      object-fit: contain;
      border: 1px solid #eee;
      border-radius: 8px;
      cursor: pointer;
    }
    
    .qrcode-loading {
      width: 200px;
      height: 200px;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      background: #f8f9fa;
      border: 1px solid #eee;
      border-radius: 8px;
      gap: 12px;
      
      .loading-text {
        font-size: 14px;
        color: #666;
        margin-top: 8px;
      }
    }
  }
  
  .pay-upload-row {
    .pay-upload-box {
      width: 200px;
      height: 200px;
      border: 2px dashed #ddd;
      border-radius: 8px;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      
      &:hover {
        border-color: #157658;
      }
      
      .pay-upload-plus {
        font-size: 40px;
        color: #ddd;
        margin-bottom: 10px;
      }
      
      .pay-upload-text {
        font-size: 14px;
        color: #999;
      }
    }
    
    // 上传后的容器样式
    .uploaded-file-container {
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 12px;
      
      .pay-qrcode {
        width: 120px;
        height: 120px;
        object-fit: cover;
        border: 1px solid #eee;
        border-radius: 8px;
        cursor: pointer;
        display: block;
        transition: all 0.3s ease;
        
        &:hover {
          border-color: #157658;
          transform: scale(1.02);
        }
      }
      
      .pay-video {
        width: 120px;
        height: 120px;
        object-fit: contain;
        border: 1px solid #eee;
        border-radius: 8px;
        cursor: pointer;
        display: block;
        transition: all 0.3s ease;
        background: #000;
        
        &:hover {
          border-color: #157658;
          transform: scale(1.02);
        }
        
        // 确保视频正确显示
        &::-webkit-media-controls {
          display: flex;
        }
        
        &::-webkit-media-controls-panel {
          background: rgba(0, 0, 0, 0.7);
        }
      }
      
      .video-actions {
        display: flex;
        gap: 8px;
        flex-wrap: wrap;
        justify-content: center;
      }
      
      .reupload-btn {
        --van-button-small-height: 30px;
        --van-button-small-padding: 0 16px;
        --van-button-small-font-size: 13px;
        --van-button-border-radius: 15px;
        --van-button-warning-background: #ff976a;
        --van-button-warning-border-color: #ff976a;
        
        &:hover {
          --van-button-warning-background: #ff7043;
          --van-button-warning-border-color: #ff7043;
        }
        
        &:active {
          transform: scale(0.95);
        }
      }
      
      .view-recognition-btn {
        --van-button-small-height: 30px;
        --van-button-small-padding: 0 16px;
        --van-button-small-font-size: 13px;
        --van-button-border-radius: 15px;
        --van-button-primary-background: #157658;
        --van-button-primary-border-color: #157658;
        
        &:hover {
          --van-button-primary-background: #0f5a47;
          --van-button-primary-border-color: #0f5a47;
        }
        
        &:active {
          transform: scale(0.95);
        }
      }
    }
  }
}

.bottom-container {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  border-top: 1px solid #eee;
  padding: 15px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  
  .price-summary {
    .total-label {
      font-size: 14px;
      color: #666;
      margin-right: 10px;
    }
    
    .total-price {
      font-size: 18px;
      color: #157658;
      font-weight: bold;
    }
  }
  
  .submit-btn {
    width: 120px;
    height: 44px;
    background: #157658;
    border: none;
    
    &:disabled {
      background: #ccc;
    }
  }
}

/* 视频帮助弹窗样式 */
.video-help-dialog {
  .van-dialog__content {
    padding: 20px;
  }
}

.video-help-content {
  .help-video {
    width: 100%;
    height: 300px;
    border-radius: 8px;
    margin-bottom: 20px;
    background: #000;
  }
  
  .video-tips {
    .tip-title {
      font-size: 16px;
      color: #333;
      font-weight: 600;
      margin-bottom: 16px;
      text-align: center;
    }
    
    .tip-list {
      display: flex;
      flex-direction: column;
      gap: 12px;
      
      .tip-item {
        display: flex;
        align-items: center;
        gap: 12px;
        padding: 8px 0;
        
        .tip-number {
          width: 24px;
          height: 24px;
          background: #157658;
          color: #fff;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 14px;
          font-weight: bold;
          flex-shrink: 0;
        }
        
        span:last-child {
          font-size: 14px;
          color: #666;
          line-height: 1.5;
        }
      }
    }
    
    .format-tips {
      margin-top: 16px;
      padding: 12px;
      background: #fff3cd;
      border: 1px solid #ffeaa7;
      border-radius: 8px;
      
      .format-warning {
        font-size: 13px;
        color: #856404;
        margin: 0;
        line-height: 1.4;
        text-align: center;
      }
    }
  }
}

/* 全屏视频播放对话框样式 */
.fullscreen-video-dialog {
  .van-dialog__content {
    padding: 0;
    max-width: 90vw;
    max-height: 80vh;
  }
}

.fullscreen-video-content {
  .fullscreen-video {
    width: 100%;
    height: 60vh;
    min-height: 300px;
    background: #000;
    border-radius: 8px;
    object-fit: contain;
  }
  
  .video-tips {
    padding: 15px 20px;
    text-align: center;
    
    .tip-text {
      font-size: 14px;
      color: #666;
      margin: 0;
    }
  }
}

/* 账单识别结果对话框样式 */
.bill-recognition-dialog {
  .van-dialog__content {
    padding: 20px;
    max-width: 90vw;
    max-height: 80vh;
    overflow-y: auto;
  }
}

.bill-recognition-content {
  .recognition-status {
    margin-bottom: 20px;
    padding: 15px;
    background: #f8f9fa;
    border-radius: 8px;
    
    .status-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10px;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .status-label {
        font-size: 14px;
        color: #333;
        font-weight: 500;
      }
      
      .status-value {
        font-size: 14px;
        font-weight: 600;
        
        &.success {
          color: #157658;
        }
        
        &.fail {
          color: #ff4757;
        }
      }
    }
  }
  
  .validation-status {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 20px;
    padding: 12px;
    border-radius: 8px;
    
    &.success {
      background: linear-gradient(135deg, #e8f5e8 0%, #d4edda 100%);
      border: 1px solid #c3e6cb;
      
      .status-text {
        margin-left: 8px;
        font-size: 16px;
        color: #157658;
        font-weight: 600;
      }
    }
    
    &.failed {
      background: linear-gradient(135deg, #ffe8e8 0%, #ffd4d4 100%);
      border: 1px solid #ffb3b3;
      
      .status-text {
        margin-left: 8px;
        font-size: 16px;
        color: #ff6b6b;
        font-weight: 600;
      }
    }
  }
  
  .validation-details {
    margin: 15px 0;
    
    .validation-error {
      display: flex;
      align-items: flex-start;
      padding: 10px;
      background: #fff5f5;
      border: 1px solid #ff6b6b;
      border-radius: 6px;
      margin-bottom: 10px;
      
      span {
        margin-left: 8px;
        color: #ff6b6b;
        font-size: 14px;
        line-height: 1.4;
      }
    }
    
    .force-submit-tips {
      display: flex;
      align-items: flex-start;
      padding: 12px;
      background: #fff8e1;
      border: 1px solid #ffcc02;
      border-radius: 6px;
      margin-top: 10px;
      
      span {
        margin-left: 8px;
        color: #ff9500;
        font-size: 14px;
        line-height: 1.4;
        font-weight: 500;
      }
    }
  }
  
  .dialog-actions {
    display: flex;
    gap: 12px;
    padding: 20px;
    border-top: 1px solid #eee;
    background: #fafafa;
    
    .action-button {
      flex: 1;
      height: 44px;
      border-radius: 8px;
      font-size: 16px;
      font-weight: 500;
      
      &.van-button--warning {
        --van-button-warning-background: #ff9500;
        --van-button-warning-border-color: #ff9500;
        --van-button-warning-color: #fff;
        
        &:hover {
          --van-button-warning-background: #e6850e;
          --van-button-warning-border-color: #e6850e;
        }
      }
    }
  }
  
  .bill-info {
    margin-bottom: 20px;
    
    .bill-title {
      font-size: 16px;
      color: #333;
      font-weight: 600;
      margin-bottom: 15px;
      text-align: center;
      padding-bottom: 10px;
      border-bottom: 2px solid #157658;
    }
    
    .bill-details {
      .bill-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 10px 0;
        border-bottom: 1px solid #eee;
        
        &:last-child {
          border-bottom: none;
        }
        
        .bill-label {
          font-size: 14px;
          color: #666;
          font-weight: 500;
        }
        
        .bill-value {
          font-size: 14px;
          color: #333;
          font-weight: 600;
          
          &.amount {
            color: #157658;
            font-size: 16px;
          }
          
          &.order-number {
            font-family: 'Courier New', monospace;
            background: #f5f5f5;
            padding: 2px 6px;
            border-radius: 4px;
            font-size: 12px;
          }
        }
      }
    }
  }
  
  .confidence-info {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 20px;
    padding: 10px;
    background: #f8f9fa;
    border-radius: 8px;
    
    .confidence-label {
      font-size: 14px;
      color: #666;
      margin-right: 10px;
    }
    
    .confidence-value {
      font-size: 16px;
      font-weight: 600;
      
      &.high {
        color: #157658;
      }
      
      &.medium {
        color: #ff976a;
      }
      
      &.low {
        color: #ff4757;
      }
    }
  }
  
  .recognition-tips {
    padding: 15px;
    background: #fff3cd;
    border: 1px solid #ffeaa7;
    border-radius: 8px;
    text-align: center;
    
    .tip-text {
      font-size: 14px;
      color: #856404;
      font-weight: 600;
      margin: 0 0 8px 0;
    }
    
    .tip-detail {
      font-size: 12px;
      color: #856404;
      margin: 0;
      line-height: 1.4;
    }
  }
  
  .confirmation-tips {
    margin-bottom: 20px;
    padding: 15px;
    background: #e3f2fd;
    border: 1px solid #bbdefb;
    border-radius: 8px;
    text-align: center;
    
    .tip-text {
      font-size: 14px;
      color: #1976d2;
      font-weight: 600;
      margin: 0 0 8px 0;
    }
    
    .tip-detail {
      font-size: 12px;
      color: #1976d2;
      margin: 0;
      line-height: 1.4;
    }
  }
}

/* 自定义Loading样式 */
.custom-loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.7);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
  backdrop-filter: blur(2px);
}

.custom-loading-content {
  background: white;
  border-radius: 12px;
  padding: 30px 40px;
  text-align: center;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
  min-width: 200px;
}

.loading-spinner {
  margin-bottom: 20px;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #1976d2;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  font-size: 16px;
  color: #333;
  font-weight: 500;
  margin: 0;
}

/* 页面锁定遮罩样式 */
.page-lock-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9998;
  backdrop-filter: blur(3px);
}

.page-lock-content {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 16px;
  padding: 40px 50px;
  text-align: center;
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.4);
  min-width: 250px;
  color: white;
}

.lock-icon {
  margin-bottom: 20px;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.1); }
  100% { transform: scale(1); }
}

.lock-text {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 10px;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.lock-tip {
  font-size: 14px;
  opacity: 0.9;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}
</style> 